package edu.intprog.sql;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * SessionManager
 *
 * This class is used for get in touch with the current hibernate session from the
 * hibernate session factory.
 * 
 * This force singletonitism
 */
public class SessionManager {
    
	private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * getSessionFactory
     * 
     * this function returns the existing session factory
     * 
     * @return hibernate session factory
     */
    private static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    /**
     * getCurrentSession
     * 
     * this function returns the current session
     * @return current hibernate session
     */
    public static Session getCurrentSession() {
    	Session session = null;
    	synchronized (sessionFactory) {
			session = sessionFactory.getCurrentSession();
		}
    	return session;
    }
}